//
//  UIView+PPKit.swift
//  PPKit
//
//  Created by xiaopin on 16/8/31.
//  Copyright © 2016年 pinguo. All rights reserved.
//  https://gitee.com/xiaopindev/PPKit
//  https://github.com/xiaopindev
//  https://xiaopin.cnblogs.com

import UIKit


public extension UIView {
    
    convenience init(frame:CGRect = .zero, bgColor: UIColor = .clear, cornerRadius:CGFloat?=nil) {
        self.init()
        self.frame = frame
        backgroundColor = bgColor
        if let c = cornerRadius {
            layer.cornerRadius = c
            layer.masksToBounds = true
        }
    }
    convenience init(_ bgColor: UIColor = .clear, cornerRadius:CGFloat?=nil) {
        self.init()
        backgroundColor = bgColor
        if let c = cornerRadius {
            layer.cornerRadius = c
            layer.masksToBounds = true
        }
    }
    
    //MARK:坐标和宽高
    var x : CGFloat {
        get {
            return self.frame.origin.x
        }
        set {
            self.frame.origin.x = newValue
        }
    }
    
    var y : CGFloat {
        get {
            return self.frame.origin.y
        }
        set {
            self.frame.origin.y = newValue
        }
    }
    
    var width : CGFloat {
        get {
            return self.frame.size.width
        }
        set {
            self.frame.size.width = newValue
        }
    }
    
    var height : CGFloat {
        get {
            return self.frame.size.height
        }
        set {
            self.frame.size.height = newValue
        }
    }

    //MARK:原点和大小

    var origin : CGPoint {
        get {
            return self.frame.origin
        }
        set {
            self.frame.origin = newValue
        }
    }
    var size: CGSize {
        get {
            return self.frame.size
        }
        set {
            self.frame.size = newValue
        }
    }
    
    //MARK:位置信息
    var bottomRight : CGPoint {
        let x : CGFloat = self.x + self.width
        let y : CGFloat = self.y + self.height
        return CGPoint(x: x, y: y)
    }
    
    var bottomLeft : CGPoint {
        let x : CGFloat = self.x
        let y : CGFloat = self.y + self.height
        return CGPoint(x: x, y: y)
    }
    
    var topRight : CGPoint {
        let x : CGFloat = self.x + self.width
        let y : CGFloat = self.y
        return CGPoint(x: x, y: y)
    }
    var top : CGFloat {
        get {
            return self.y
        }
        set {
            self.y = newValue
        }
    }
    
    /// PPExtensionKit: 左边距
    var left : CGFloat {
        get {
            return self.x
        }
        set {
            self.x = newValue
        }
    }
    
    /// PPExtensionKit:下边距
    var bottom : CGFloat {
        get {
            return self.y + self.height
        }
        set {
            self.y = newValue - self.height
        }
    }
    
    /// PPExtensionKit: 右边距
    var right : CGFloat {
        get {
            return self.x + self.width
        }
        set {
            self.x = newValue - self.width
        }
    }
    
    //MARK: 圆角和边框
    /// PPExtensionKit:圆角
    var cornerRadius: CGFloat {
        get {
            return self.layer.cornerRadius
        }
        set {
            self.layer.cornerRadius = newValue
            self.layer.masksToBounds = true
        }
    }
    
    /// PPExtensionKit:边框
    var borderColor: UIColor {
        get {
            return UIColor.init(cgColor: self.layer.borderColor!)
        }
        set {
            self.layer.borderColor = newValue.cgColor
            self.layer.borderWidth = 0.5
        }
    }
    
    /// PPExtensionKit:边框
    var borderWidth: CGFloat {
        get {
            return self.layer.borderWidth
        }
        set {
            self.layer.borderWidth = newValue
        }
    }
    
    @discardableResult
    func beAddInto(_ superView : UIView?) -> UIView {
        if let superView = superView {
            superView.addSubview(self)
        }
        return self
    }
    
    func beAddIn<T>(_ superView : UIView?) -> T {
        if let superView = superView {
            superView.addSubview(self)
        }
        return self as! T
    }
    
    //MARK: 颜色渐变
    /// 水平渐变
    ///
    /// - Parameters:
    ///   - startColor: <#startColor description#>
    ///   - endColor: <#endColor description#>
    func addGradientLayerForHorizontal(_ startColor: UIColor, _ endColor: UIColor) {
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = self.bounds
        gradientLayer.colors = [startColor.cgColor, endColor.cgColor]
        gradientLayer.startPoint = CGPoint(x: 0, y: 0)
        gradientLayer.endPoint = CGPoint(x: 1, y: 0)
        gradientLayer.locations = [0,1]
        self.layer.insertSublayer(gradientLayer, at: 0)
    }
    ///暗黑补充水平渐变

    func addGradientLayerForHorizontalforiOS13(_ startColor: UIColor, _ endColor: UIColor , darkSColor: UIColor , _ darkEndColor: UIColor) {
        if #available(iOS 13.0, *) {
            let mode = XPApplication.shared.themeMode
            if mode == .light  {
                self.addGradientLayerForHorizontal(startColor, endColor)
            }else if mode == .dark {
                self.addGradientLayerForHorizontal(darkSColor, darkEndColor)
            }else{
                //判断模式
                if traitCollection.userInterfaceStyle == .dark {
                    self.addGradientLayerForHorizontal(darkSColor, darkEndColor)
                }else {
                    self.addGradientLayerForHorizontal(startColor, endColor)
                }
            }
        }else{
            self.addGradientLayerForHorizontal(startColor, endColor)
        }
    }
    /// 垂直渐变
    ///
    /// - Parameters:
    ///   - startColor: <#startColor description#>
    ///   - endColor: <#endColor description#>
    func addGradientLayerForVertical(_ startColor: UIColor, _ endColor: UIColor) {
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = self.bounds
        gradientLayer.colors = [startColor.cgColor, endColor.cgColor]
        gradientLayer.startPoint = CGPoint(x: 0, y: 0)
        gradientLayer.endPoint = CGPoint(x: 0, y: 1)
        gradientLayer.locations = [0,1]
        self.layer.insertSublayer(gradientLayer, at: 0)
    }
    
    func removeGradientLayer(){
        for lay in self.layer.sublayers!{
            if lay.isKind(of: CAGradientLayer.self){
                lay.removeFromSuperlayer()
            }
        }
    }
    
    enum ShadowType: Int {
        case all = 0 ///四周
        case top  = 1 ///上方
        case left = 2///左边
        case right = 3///右边
        case bottom = 4///下方
    }

    /*
     用法：
     let itemView = UIView.init(frame: CGRect.init(x: 100, y: 120, width: 100, height: 100))
     itemView.backgroundColor = .red
     itemView.shadow(.all)
     itemView.tag = 10000
     view.addSubview(itemView)
     **/
    ///默认设置：黑色阴影
    func shadow(_ type: ShadowType) {
        shadow(type: type, color: .black, opactiy: 0.4, shadowSize: 4)
    }
    ///常规设置
    func shadow(type: ShadowType, color: UIColor = .black,  opactiy: Float = 0.4, shadowSize: CGFloat = 4, cornerRadius:CGFloat = 0) -> Void {
        layer.cornerRadius = cornerRadius//圆角
        layer.masksToBounds = false;//必须要等于NO否则会把阴影切割隐藏掉
        setLayerShadowColor(color)
//        layer.shadowColor = color.cgColor;// 阴影颜色
        layer.shadowOpacity = opactiy;// 阴影透明度，默认0
        layer.shadowOffset = CGSize(width: 0, height: 0);//shadowOffset阴影偏移，默认(0, -3),这个跟shadowRadius配合使用
        layer.shadowRadius = shadowSize //阴影半径，默认3
        var shadowRect: CGRect?
        switch type {
        case .all:
            shadowRect = CGRect.init(x: -shadowSize, y: -shadowSize, width: bounds.size.width + 2 * shadowSize, height: bounds.size.height + 2 * shadowSize)
        case .top:
            shadowRect = CGRect.init(x: -shadowSize, y: -shadowSize, width: bounds.size.width + 2 * shadowSize, height: 2 * shadowSize)
        case .bottom:
            shadowRect = CGRect.init(x: -shadowSize, y: bounds.size.height - shadowSize, width: bounds.size.width + 2 * shadowSize, height: 2 * shadowSize)
        case .left:
            shadowRect = CGRect.init(x: -shadowSize, y: -shadowSize, width: 2 * shadowSize, height: bounds.size.height + 2 * shadowSize)
        case .right:
            shadowRect = CGRect.init(x: bounds.size.width - shadowSize, y: -shadowSize, width: 2 * shadowSize, height: bounds.size.height + 2 * shadowSize)
        }
        layer.shadowPath = UIBezierPath.init(rect: shadowRect!).cgPath
    }
    
    /// 圆角加边框
    func makeCornerRadius(_ cornerRadius : CGFloat?=nil,borderColor:UIColor?=nil,borderWidth:CGFloat?=nil,backgroundColor:UIColor?=nil) {
        if let cornerRadius = cornerRadius {
            self.layer.cornerRadius = cornerRadius
            self.layer.masksToBounds = true
        }
        if let borderColor = borderColor {
            setLayerBorderColor(borderColor)
        }
        if let borderWidth = borderWidth {
            self.layer.borderWidth = borderWidth
        }
        if let backgroundColor = backgroundColor {
            self.backgroundColor = backgroundColor
        }
    }
    
    /// 获取当前视图控制器
    func viewcontroller() -> UIViewController? {
        var next = self.next

        while (next != nil) {
            if (next is UIViewController) {
                return next as? UIViewController
            }
            next = next?.next
        }
        return nil
    }
    
    /// 获取当前视图导航控制器
    func navigationcontroller() -> UINavigationController? {
        var next = self.next

        while (next != nil) {
            if (next is UINavigationController) {
                return next as? UINavigationController
            }
            next = next?.next
        }
        return nil
    }
    
    /// 部分圆角
    ///
    /// - Parameters:
    ///   - corners: 需要实现为圆角的角，可传入多个
    ///   - radii: 圆角半径
    /// AaaaView.corner(byRoundingCorners: [.topLeft, .topRight], radii: 3)
    func corner(byRoundingCorners corners: UIRectCorner, radii: CGFloat) {
        let maskPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radii, height: radii))
        let maskLayer = CAShapeLayer()
        maskLayer.path = maskPath.cgPath
        self.layer.mask = maskLayer
    }
    
    ///部分圆角加阴影
    ///
    /// - Parameters:
    ///   - corners: 需要实现为圆角的角，可传入多个
    ///   - radii: 圆角半径
    ///   - bgColor: 背景颜色
    ///   - shadowColor: 阴影颜色
    ///   - opactiy: 阴影透明度
    ///   - shadowSize: 阴影偏移量
    func cornerAndShadow(corners: UIRectCorner, radii: CGFloat, bgColor:UIColor, shadowColor: UIColor = .black, opactiy: Float = 0.4, shadowSize: CGFloat = 4){
        //清空空间自身的背景颜色
        backgroundColor = UIColor.clear
        //绘制部分圆角曲线路径
        let maskPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radii, height: radii))
        //创建阴影图层：单独的阴影方向，可以控制shadowLayer.frame，现在只默认实现全部包围的阴影
        let shadowLayer = CAShapeLayer()
        shadowLayer.frame = CGRect(origin: bounds.origin, size: CGSize(width: bounds.size.width + shadowSize * 2, height: bounds.size.height + shadowSize * 2))
        shadowLayer.masksToBounds = false
        shadowLayer.shadowPath = maskPath.cgPath//阴影路径
        shadowLayer.setShadowColor(shadowColor, with: self)
//        shadowLayer.shadowColor = shadowColor.cgColor//阴影颜色
        shadowLayer.shadowOffset = .zero
        shadowLayer.shadowOpacity = opactiy
        shadowLayer.shadowRadius = shadowSize
        //创建圆角图层，使用圆角图层蒙版
        let roundedLayer = CALayer()
        roundedLayer.frame = bounds
        roundedLayer.setBackgroundColor(bgColor, with: self)
//        roundedLayer.backgroundColor = bgColor.cgColor
        let maskLayer = CAShapeLayer()
        maskLayer.frame = bounds
        maskLayer.path = maskPath.cgPath
        roundedLayer.mask = maskLayer
        //添加到最底层
        layer.insertSublayer(roundedLayer, at: 0)
        layer.insertSublayer(shadowLayer, at: 0)
    }
    
    ///部分圆角加边框
    ///
    /// - Parameters:
    ///   - corners: 需要实现为圆角的角，可传入多个
    ///   - radii: 圆角半径
    ///   - borderColor: 边框颜色
    ///   - borderWidth: 边框宽度
    func cornerAndBorder(corners: UIRectCorner, radii: CGFloat, borderColor:UIColor, borderWidth:CGFloat){
        let maskPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radii, height: radii))
        let maskLayer = CAShapeLayer()
        maskLayer.path = maskPath.cgPath
        self.layer.mask = maskLayer
        
        // 拿到当前的layer，重新绘制边框
        let borderLayer = CAShapeLayer()
        borderLayer.path = maskLayer.path
        borderLayer.fillColor = UIColor.clear.cgColor
        borderLayer.setStrokeColor(borderColor, with: self)
//        borderLayer.strokeColor = borderColor.cgColor
        borderLayer.lineWidth = borderWidth
        borderLayer.frame = self.bounds
        self.layer.addSublayer(borderLayer)
    }
    /// 添加多个View
    func addSubviews(_ arr:[UIView]){
        for obj in arr {
            self.addSubview(obj)
        }
    }
    /// 点击事件
    func addTap(target:Any,action:Selector){
        self.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target:target,action:action)
        addGestureRecognizer(tap)
    }
    
    /// 长按事件
    func addLongTap(target:Any,action:Selector){
        self.isUserInteractionEnabled = true
        let tap = UILongPressGestureRecognizer(target:target,action:action)
        tap.minimumPressDuration = 1
        addGestureRecognizer(tap)
    }
    
    /// 跳转
    func pushVC(_ targetVc:UIViewController) {
        let nav = viewcontroller()?.navigationController
        nav?.pushViewController(targetVc,animated:true)
    }
}

protocol NibLoadable {}
extension NibLoadable where Self : UIView {
    //在协议里面不允许定义class 只能定义static
    
    /// 获取 xib UIView 对象
    ///
    /// - Parameter nibname: <#nibname description#>
    /// - Returns: <#return value description#>
    static func loadFromNib(_ nibname: String? = nil) -> Self {//Self (大写) 当前类对象
        //self(小写) 当前对象
        let loadName = nibname == nil ? "\(self)" : nibname!
        return Bundle.main.loadNibNamed(loadName, owner: nil, options: nil)?.first as! Self
    }
}

